
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.abm.jwebsite.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Saptarshi Debnath (saptarshi.devnath@gmail.com)
 */
public class XMLParser {

    public static NodeList parse(File xmlFile, String xPathExpression) throws ParserConfigurationException, XPathExpressionException, SAXException, IOException {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document xmlDocument = builder.parse(new FileInputStream(xmlFile));
        XPath xPath = XPathFactory.newInstance().newXPath();
        return ((NodeList) xPath.compile(xPathExpression).evaluate(xmlDocument, XPathConstants.NODESET));
    }

    public static String getAttributeValue(Node node, String attributeName) {
        String attributeValue = null;
        NamedNodeMap attributeMap = node.getAttributes();
        attributeValue = (attributeMap.getNamedItem(attributeName) == null) ? "" : attributeMap.getNamedItem(attributeName).getNodeValue().toString();
        return attributeValue;
    }

    public static Map<String, String> getAttributeValue(Node node, String[] attributeNames) {
        Map<String, String> map = new HashMap<String, String>();
        for (String attribute : attributeNames) {
            map.put(attribute, XMLParser.getAttributeValue(node, attribute));
        }
        return map;
    }
}
